<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :is-fullscreen="true" width="1200">
    <div class="form-container">
      <div class="left-form">
        <el-card class="article-form-card">
          <template #header>
            <span>文章表单</span>
          </template>
          <el-form
            ref="formRef1"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            v-loading="formLoading"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入文章标题"/>
            </el-form-item>
            <el-form-item label="摘要" prop="abstracts">
              <el-input v-model="formData.abstracts" type="textarea" placeholder="请输入摘要"/>
            </el-form-item>
            <el-form-item label="文章内容" prop="content">
              <Editor v-model="formData.content"/>
            </el-form-item>
            <el-form-item label="文章首页图片" prop="imgs">
              <UploadImgs v-model="formData.imgs" :limit="10"/>
            </el-form-item>
            <el-form-item label="文章视频" prop="video">
              <UploadFile v-model="formData.video" :file-size="50" :limit="1"/>
            </el-form-item>
            <el-form-item label="文章类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择文章类型">
                <el-option
                  v-for="dict in getStrDictOptions('cms_article_type')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="测试标记" prop="testStatus">
              <el-select v-model="formData.testStatus" placeholder="请选择测试标记">
                <el-option
                  v-for="dict in getStrDictOptions('cms_test_status')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分类" prop="classifyId">
              <el-tree-select
                v-model="formData.classifyId"
                :data="classifyTree"
                :props="defaultProps"
                check-strictly
                multiple
                default-expand-all
                @change="setShowResource"
              />
            </el-form-item>
            <el-divider>
              <span :style="{ color: '#999', fontSize: '12px' }">软件资源</span></el-divider>
            <el-form-item label="资源目录" prop="dir" v-if="showResource">
              <el-select v-model="formData.dir" placeholder="请输入资源目录">
                <el-option
                  v-for="item in dirList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="价格" prop="price" v-if="showResource">
              <el-input-number :min="1" v-model="formData.price" placeholder="请输入价格"/>
            </el-form-item>
            <el-form-item label="收费模式" prop="chargeType" v-if="showResource">
              <el-select v-model="formData.chargeType" placeholder="请选择收费模式">
                <el-option
                  v-for="dict in getStrDictOptions('cms_charge_type')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="VIP优惠" prop="vipDiscounts" v-if="showResource">
              <el-select v-model="formData.vipDiscounts" placeholder="请选择VIP优惠">
                <el-option
                  v-for="dict in getStrDictOptions('cms_vip_discounts')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div class="right-form">
        <div style="text-align: right; margin-bottom: 10px">
          <el-button type="primary" plain @click="handlePreview">预览</el-button>
        </div>
        <divider property=""/>
        <el-card class="push-form-card">
          <template #header>
            <span>发布</span>
          </template>
          <el-form-item label="状态" prop="draft" :label-position="'top'">
            <el-radio-group v-model="formData.draft">
              <el-radio value="草稿">草稿</el-radio>
              <el-radio value="非草稿">非草稿</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="可见性" prop="visibility" :label-position="'top'">
            <el-radio-group v-model="formData.visibility">
              <el-radio value="公开">公开</el-radio>
              <el-radio value="非公开">非公开</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="置顶文章" prop="top" :label-position="'top'">
            <el-radio-group v-model="formData.top">
              <el-radio :value="1">置顶</el-radio>
              <el-radio :value="0">非置顶</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-card>
        <el-card class="pic-form-card">
          <template #header>
            <span>特殊图片</span>
          </template>
          <el-form-item
            label="外链特色图片地址（留空即删除）："
            prop="specialPic"
            :label-position="'top'"
          >
            <el-input v-model="formData.specialPic" placeholder=""/>
          </el-form-item>
        </el-card>
        <el-card class="tag-form-card">
          <template #header>
            <span>标签</span>
          </template>
          <el-select v-model="formData.signId" clearable filterable multiple placeholder="请选择">
            <el-option
              v-for="dict in signList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>

          <div style="display: flex; gap: 10px; margin-top: 10px">
            <el-input v-model="signName" placeholder=""/>
            <el-button type="primary" plain @click="submitSign">添加</el-button>
          </div>
        </el-card>
        <el-card class="classify-form-card">
          <template #header>
            <span>分类</span>
          </template>
          <el-form
            ref="formRef2"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            v-loading="formLoading"
          >
            <el-form-item label="分类" prop="classifyId" label-position="top">
              <el-tree-select
                v-model="formData.classifyId"
                :data="classifyTree"
                :props="defaultProps"
                check-strictly
                multiple
                default-expand-all
                @change="setShowResource"
              />
            </el-form-item>
          </el-form>
          <el-link type="primary" @click="openClassifyForm">+ 添加新分类</el-link>
        </el-card>
      </div>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：添加/修改 -->
  <ClassifyForm ref="classifyFormRef" @success="getClassifyTree"/>
</template>
<script setup lang="ts">
import {getStrDictOptions} from '@/utils/dict'
import {ArticleApi, ArticleVO} from '@/api/system/article'
import {defaultProps, handleTree} from '@/utils/tree'
import {ClassifyApi} from '@/api/system/classify'
import {ArticleSignApi} from '@/api/system/articlesign'
import {ResourceDirApi} from "@/api/system/resourcedir";
import ClassifyForm from "@/views/system/classify/ClassifyForm.vue";
import Divider from "@/components/DiyEditor/components/mobile/Divider/index.vue";

/** 文章 表单 */
defineOptions({name: 'ArticleForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const classifyTree = ref() // 树形结构
const classifyList = ref() // 树形结构
const signList = ref() // 标签
const dirList = ref([]) // 资源目录
const classify = ref()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  abstracts: undefined,
  content: undefined,
  classifyId: [],
  imgs: undefined,
  video: undefined,
  type: undefined,
  testStatus: undefined,
  dir: undefined,
  price: undefined,
  chargeType: undefined,
  vipDiscounts: undefined,
  activityUrl: undefined,
  activityCode: undefined,
  specialPic: undefined,
  signId: undefined,
  draft: '非草稿',
  visibility: '公开',
  top: 0,
  tips: undefined
})
const signName = ref()
const formRules = reactive({
  title: [{required: true, message: '文章标题不能为空', trigger: 'blur'}],
  content: [{required: true, message: '文章内容不能为空', trigger: 'blur'}],
  classifyId: [{required: true, message: '分类ID不能为空', trigger: 'blur'}],
  imgs: [{required: true, message: '图片不能为空', trigger: 'blur'}],
  type: [{required: true, message: '类型不能为空', trigger: 'blur'}],
  chargeType: [{required: true, message: '收费模式不能为空', trigger: 'blur'}],
  vipDiscounts: [{required: true, message: 'VIP优惠不能为空', trigger: 'blur'}],
  testStatus: [{required: true, message: '测试标记不能为空', trigger: 'blur'}],
  dir: [{required: true, message: '资源目录不能为空', trigger: 'blur'}],
  price: [{required: true, message: '价格不能为空', trigger: 'blur'}]
})

/** 添加/修改操作 */
const classifyFormRef = ref()
const openClassifyForm = () => {
  classifyFormRef.value.open('新增分类')
}

const formRef1 = ref() // 表单 Ref
const formRef2 = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ArticleApi.getArticle(id)
    } finally {
      formLoading.value = false
    }
  }
  await getClassifyTree()
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitSign = async () => {
  if (signName && signName.value) {
    const data = {name: signName.value, alias: signName.value}
    console.log(data)
    await ArticleSignApi.createArticleSign(data)
    message.success(t('common.createSuccess'))
    ArticleSignApi.getArticleSignList().then((data) => {
      signList.value = data
    })
    signName.value = ''
  } else {
    message.error('不要输入空值')
  }
}
const submitForm = async (val?:string) => {
  // 校验表单
  if (val==='预览'){
    await formRef2.value.validate()
  }else{
    await formRef1.value.validate()
    await formRef2.value.validate()
  }
  // 提交请求
  formLoading.value = true
  let id: number = 0;
  try {
    const data = formData.value as unknown as ArticleVO
    if (formType.value === 'create') {
      id = await ArticleApi.createArticle(data);
      message.success(t('common.createSuccess'))
    } else {
      await ArticleApi.updateArticle(data)
      message.success(t('common.updateSuccess'))
      id = data.id;
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    return id
  } finally {
    formLoading.value = false
  }
}

/**
 * 软件下载ID==11
 */
const showResource = ref(false)

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    abstracts: undefined,
    content: undefined,
    classifyId: [],
    imgs: undefined,
    video: undefined,
    type: undefined,
    testStatus: undefined,
    dir: undefined,
    price: undefined,
    chargeType: undefined,
    vipDiscounts: undefined,
    activityUrl: undefined,
    activityCode: undefined,
    draft: '非草稿',
    visibility: '公开',
    top: 0,
    tips: undefined
  }
  formRef1.value?.resetFields()
  formRef2.value?.resetFields()
}

/** 获得分类树 */
const getClassifyTree = async () => {
  classifyTree.value = []
  const data = await ClassifyApi.getClassifyList()
  classifyList.value = data
  const root: Tree = {id: 0, name: '顶级分类', children: []}
  root.children = handleTree(data, 'id', 'parentId')
  classifyTree.value.push(root)

  if (formData.value) {
    await setShowResource()
  }
}

const setShowResource = async () => {
  classify.value = classifyList.value.filter((item) => formData.value.classifyId.includes(item.id))
  const parentIdList = classify.value.map(item => item.parentId);
  console.log(classify.value, 'classify', formData.value.classifyId, parentIdList)

  showResource.value = parentIdList.includes(2) || formData.value.classifyId.includes(2)
}

const handlePreview = async () => {
  console.log('预览')
  formData.value.draft = '草稿'
  submitForm('预览').then((res) => {
    console.log('保存成功', res)
    // 打开外链链接
    window.open(`https://search.modou.tv/#/down/detail/${res}`)
  }).catch(() => {
    message.error('未填写必填项')
  })
}

onMounted(async () => {
  ArticleSignApi.getArticleSignList().then((data) => {
    signList.value = data
  })

  ResourceDirApi.getResourceDirList().then((data) => {
    console.log('data', data)
    dirList.value = data
  })
})
</script>
<style scoped lang="scss">
.form-container {
  display: flex;
  gap: 20px;
}

.left-form {
  width: 80%;
}

.right-form {
  width: 20%;
}

.article-form-card {
  height: 100%;
}

.push-form-card {
  margin-bottom: 10px;
}

.pic-form-card {
  margin-bottom: 10px;
}

.tag-form-card {
  margin-bottom: 10px;
}

.classify-form-card {
  margin-bottom: 10px;
}

.article-form {
  --el-input-bg-color: #f9f9f9;
  --el-input-border-color: #e4e4e4;
  --el-input-hover-border-color: #999;
  --el-select-bg-color: #f9f9f9;
  --el-select-border-color: #e4e4e4;
  --el-select-hover-border-color: #999;

  el-form-item {
    margin-bottom: 15px;
  }

  el-input,
  el-select {
    width: 100%;
  }

  el-textarea__inner {
    min-height: 100px;
  }
}
</style>
